import { defineStore } from 'pinia';
// import { watch } from 'vue';
// import { useRouter } from 'vue-router';
// import Router from '../router/index'

const AUTO_LOGOUT_TIME = 60 * 60 * 60 * 60; // 以毫秒为单位

export const useAuthStore = defineStore({
    id: 'auth',
    state: () => ({
        user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')!) : null,
        logoutTimer: null as number | null,
    }),
    getters: {
        isLoggedIn: (state) => !!state.user,
    },
    actions: {
        login(user: any) {
            this.user = user;
            this.user.images = "http://localhost:8086/getImage?filename=" + user.image;
            localStorage.setItem('user', JSON.stringify(this.user));
            this.startLogoutTimer();
        },
        logout() {
            // if (Router.currentRoute.value.name !== 'login') {
            //     Router.push({ name: 'login' });
            // }
			uni.redirectTo({
			  url: '/pages/login/index'
			});
            this.user = null;
            localStorage.removeItem('user');
            this.clearLogoutTimer();
        },
        images(fileName: any, data: any) {
            if (this.user != null) {
                this.user.image = fileName;
                this.user.images = data;
                localStorage.setItem('user', JSON.stringify(this.user));
            }
        },
        startLogoutTimer() {
            this.clearLogoutTimer();
            this.logoutTimer = setTimeout(() => {
                this.logout();
            }, AUTO_LOGOUT_TIME);
        },
        clearLogoutTimer() {
            if (this.logoutTimer !== null) {
                clearTimeout(this.logoutTimer);
                this.logoutTimer = null;
            }
        },
    },
});